#!/usr/bin/env python
# -*- coding: utf-8 -*-

# ===================
# Author: Huang Gang
# Date: 2017-09-18
# ===================
import web
import os
# from string import strip
import config
from utils.log import log

web.config.debug = False

# app = web.application(urls, locals())

render = web.template.render('templates')
urls = (
    '/', 'app.controllers.account.index',
    '/register', 'app.controllers.account.register',
    '/vcode', 'app.controllers.account.vcode',
    '/cd', 'app.controllers.account.cd',
    '/login', 'app.controllers.account.login',
    '/logout', 'app.controllers.account.logout',
    '/relogin', 'app.controllers.account.relogin',
    '/forget_password', 'app.controllers.account.forget_password',
    '/send_link', 'send_link',
    '/reset_page', 'reset_page',
    '/reset_password', 'reset_password',
    '/return_to_login', 'return_to_login',
    '/personal_center', 'app.controllers.account.personal_center',
    '/study/?', 'app.controllers.account.study',
    '/code', 'app.controllers.account.code',
    '/code_is_running', 'app.controllers.account.code_is_running',
    '/runcode', 'app.controllers.account.runcode',
    '/rerun', 'app.controllers.account.rerun',
    '/update_password', 'app.controllers.account.update_password',
    '/get_vcode', 'app.controllers.account.get_vcode',
    '/generate_verifycode', 'app.controllers.account.generate_verifycode',
    '/save_strategy', 'app.controllers.account.save_strategy',
    '/save_comment', 'app.controllers.account.save_comment',
    '/subscribe', 'app.controllers.account.subscribe',
    '/validation_strategy_name', 'app.controllers.account.validation_strategy_name',
    '/validation_islogin', 'app.controllers.account.validation_islogin',
    '/current_user', 'app.controllers.account.current_user',

    '/verification', 'app.controllers.account.verification',
    '/verification_for_update_password', 'app.controllers.account.verification_for_update_password',
    '/tactics_detail?', 'app.controllers.account.tactics_detail',
    '/service', 'service',
    '/help', 'app.controllers.account.help',

    '/settings', 'app.controllers.settings.index',
    '/settings/change_nickname', 'app.controllers.settings.change_nickname',
    '/settings/change_password', 'app.controllers.settings.change_password',
    '/settings/change_email', 'app.controllers.settings.change_email',
    "/count", "count",
    "/reset", "reset",

    '/(?:img|js|css)/.*', 'app.controllers.public.public',

    '/(|new|all|admitted)', 'app.controllers.browse.list',
    '/applicant/(\d+)', 'app.controllers.browse.show',
)

#=======================================================
# This function is used to create the code from the user
#=======================================================
def create_file(file1, file2):
    file_origin = open(file1, "r")
    content = file_origin.read()
    content_add = ""
    pos = content.find("#insert above")

    #if the code is not written in the file 'file2', then pass.
    if os.path.getsize(file2) == 0:
        content = content[:pos] + "    pass\n" + content[pos:]
    else:
        file_add = open(file2, "r")
        while 1:
            line = file_add.readline()
            if not line:
                break
            new_line = "    " + line.rstrip() + '\n'
            content_add = content_add + new_line
        content = content[:pos] + content_add + content[pos:]
        file_add.close()

    file_origin = open("./new_sim.py", "w")
    file_origin.write(content)
    file_origin.close()

def write_data(data):
    output_file = open('output.py', 'wb')
    output_file.write(data)
    output_file.close()

def verification(phonenumber, key):
    return (config.sjk.user_coll.find({"user_phone": phonenumber, "user_md5": key}).count() == 1)

def md5(pwd):
    import hashlib
    m = hashlib.md5()
    m.update(pwd)
    return m.hexdigest()

class service:
    def GET(self):
        # raise web.seeother('/service')
        return service()

class forget_password:
    def GET(self):
        return render.forget_password()


class send_link:
    def POST(self):
        user_input = web.input()
        email = user_input['email']
        verification = user_input['verification']
        # 输入验证码
        host = 'smtp.163.com'
        from_addr = 'gang.huang@capital.cn'
        password = '9861108xt'
        # to_addr = email
        to_addr = '530419350@qq.com'
        subject = '请点击以下链接进行密码重置'
        content = """
        <p><a href="http://0.0.0.0:8080/reset_page">请点击此链接进行密码修改</a></p>
        """
        send_email(host, from_addr, password, to_addr, subject, content)
        return render.send_link()

class reset_page:
    def GET(self):
        return render.reset_page()

class reset_password:
    def POST(self):
        a = []
        user_input = web.input()
        username = user_input['username']
        password = user_input['password']
        if (config.sjk.user_coll.find({"user_id": username}).count() == 0):
            return render.reset_fail()
        else:
            cursor = config.sjk.user_coll.find({"user_id": username})
            for c in cursor:
                a.append(c["user_phone"])
            phonenumber = a[0]
            md5_pn = md5(phonenumber)
            md5_pw = md5(password)
            md5_f = md5(md5_pn + md5_pw)
            u = config.sjk.user_coll.update({"user_phone": phonenumber}, {"$set": {"user_md5": md5_f}})
            return render.reset_password()


# After pushing the "confirm" button, go to the page '/'.
# Use POST() method, instead of GET()
class return_to_login:
    def POST(self):
        raise web.seeother('/')

class user_center:
    def POST(self):
        return render.user_center()



from web.session import Store
import time
db =config.sjk

class MongoStore(Store):
    def __init__(self, db, collection_name):
        self.collection = db[collection_name]

    def __contains__(self, key):
        data = self.collection.find_one({'session_id':key})
        return bool(data)

    def __getitem__(self, key):
        now = time.time()
        s = self.collection.find_one({'session_id':key})
        if not s:
            raise KeyError
        else:
            s.update({'attime':now})
            return s

    def __setitem__(self, key, value):
        now = time.time()

        value['attime'] = now

        s = self.collection.find_one({'session_id':key})
        if s:
            value = dict(map(lambda x: (str(x[0]), x[1]), [(k,v) for (k,v) in value.iteritems() if k not in ['_id']]))
            s.update(**value)
            self.collection.save(s)
        else:
            self.collection.insert(value)

    def __delitem__(self, key):
        self.collection.remove({'session_id':key})

    def cleanup(self, timeout):
        timeout = timeout/(24.0*60*60) #timedelta takes numdays as arg
        last_allowed_time = time.time() - timeout
        self.collection.remove({'attime' : { '$lt' : last_allowed_time}})

#web.config.session_parameters['timeout'] = 186400
#web.config.session_parameters['ignore_expiry'] = True
#web.config.session_parameters['ignore_change_ip'] = False

app = web.application(urls, globals())
session = web.session.Session(app, MongoStore(db,'sessions'), initializer={'usrs': {}})
main_session = session._initializer

if __name__ == "__main__":
    web.wsgi.runwsgi = lambda func, addr=None: web.wsgi.runfcgi(func, addr)
    app.run()
